package com.woniu.cms.psm.core.exception;

import com.woniu.common.api.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lbhstart
 * @create 2022-09-06 15:47
 */
@RestControllerAdvice
public class GlobalException {

    /**
     * 对没有通过校验的异常处理
     * @param methodArgumentNotValidException
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handlerMethodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException){
        List<FieldError> fieldErrors = methodArgumentNotValidException.getBindingResult().getFieldErrors();
        Map<String, String> map = fieldErrors.stream().collect(Collectors.toMap(
                FieldError::getField,
                FieldError::getDefaultMessage
        ));
        return Result.error(map);
    }

    /**
     * 兜底全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handlerException(Exception e){
        return Result.error(e.getMessage());
    }

}
